package com.kou.backend.filter;

import com.kou.backend.property.JwtProperties;
import com.kou.backend.util.JwtTokenUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT登录过滤器
 * 配合Security
 *
 * @author: Chaojie.Kou
 * @since: 2023/8/30 17:15
 */
@Slf4j
public class RequestJwtTokenFilter extends OncePerRequestFilter {
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private JwtTokenUtils jwtTokenUtils;
    @Resource
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authToken = request.getHeader(jwtProperties.getTokenHeader());
        //判断token是否合法
        if (StringUtils.isNotBlank(authToken)) {
            String userAccount = (String) jwtTokenUtils.getClaimsFromToken(authToken).get("userAccount");
            log.info("checking user:{}", userAccount);
            if (userAccount != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(userAccount);
                //验证用户token是否有效
                if (jwtTokenUtils.verify(authToken)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    log.info("authenticated user:{}", userAccount);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    log.info("RequestJwtTokenFilter: ,principal = {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
                    //刷新用户jwt令牌
                    jwtTokenUtils.refreshToken(authToken);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
